<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\Responder;
use StudyBuddy\WebPage;
use StudyBuddy\Request;

/**
 * Controller for rendering
 * the "Members" page
 *
 * If request is by Ajax, it returns only the content
 * of the main area, paginated, sorted and with pagination
 * links if necessary
 *
 */
class Deleteresource extends WebPage {

    protected function main() {
        $this->permission = 'delete_resource';

        $this->checkPermission()
                ->delete()
                ->returnResult();
    }

    /**
     * If Viewer has permission to delete_resource
     * then do nothing, else sets the $this->viewerId to uid of viewer
     * which is passed to CommentParser->delete() as 2nd param
     * and causes the comment ownership check
     *
     * @return object $this
     */
    protected function checkPermission() {
        try {
            $this->checkAccessPermission($this->permission);
        } catch (\Exception $e) {
            $this->viewerId = $this->oRegistry->Viewer->getUid();
        }

        return $this;
    }

    /**
     * 
     * Use CommentParser to delete a comment
     * Using CommentParser is the only way to delete
     * comment. This way API can use it too without
     * duplicationg lots of code
     * 
     * @return object this
     */
    protected function delete() {
        if($this->oRegistry->Viewer->isAdmin()) {
            $this->rid = $this->oRegistry->Request->get('rid', 'i', 0);
            $where = array('_id' => $this->rid);
            $this->oRegistry->Mongo->RESOURCE_DOCS->remove($where);
        }

        return $this;
    }

    /**
     * Return empty array via Ajax
     * this way UI will not have to do anything
     * 
     * 
     */
    protected function returnResult() {
        if (Request::isAjax()) {
            Responder::sendJSON(array());
        }

        Responder::redirectToPage();
    }

}
